import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Model {
	public final Logger logger = Logger.getGlobal();
	Gson gson = new Gson();
	File file = null;// 文件
	String file_type = null;// 文件类型
	String file_text = null;// 文件内容
	String regular_expression = Settings.default_regular_expression;// 断章正则表达式
	String last_open = Settings.setting_map.get("last_open").toString();
	ColorStyle color_style = ColorStyle.WRITE;
	HashMap<String, Integer> catalog_map = new HashMap<>();// 目录
	HashMap<String, Integer> book_mark_map = new HashMap<>();
	HashMap<String, HashMap<String, Integer>> book_map = new HashMap<>();
	Controller control;

	Model(ReaderFrame frame) {
		logger.setLevel(Level.INFO);
		ConsoleHandler c_handler = new ConsoleHandler();
		c_handler.setFormatter(new SimpleFormatter());
		logger.addHandler(c_handler);

		control = new Controller(this, frame);
		String cache = Settings.setting_map.get("regular_expression").toString();
		if (cache != null)
			regular_expression = cache;// 读取最后阅读路径

		String cache_style = Settings.setting_map.get("color_style").toString();
		if (cache_style != null)
			color_style = gson.fromJson(cache_style, ColorStyle.class);// 读取颜色设置

		if (last_open != null) {
			file = new File(last_open);
			if (file.exists() && file.isFile())
				control.displayFile(this);
		}
		book_map = gson.fromJson(Settings.setting_map.get("book_map").toString(), HashMap.class);
        System.out.println(book_map.toString());
		if (book_map.containsKey(file.getName())) {
			try {
				book_mark_map = gson.fromJson(String.valueOf(book_map.get(file.getName())), HashMap.class);
				System.out.println(book_map);
			} catch (Exception ex) {
				//ex.printStackTrace();
				logger.warning(ex.getMessage());
			}
		}
	}

	public static Matcher matcher(String matcherString, String compileString) {
		Pattern pattern = Pattern.compile(compileString);
		return pattern.matcher(matcherString);
	}

}
